using System.IO;
using Newtonsoft.Json;
using System;

namespace NExt.Serialization.JsonNet.Conversion
{
    public abstract class AbstractJsonConvertor<TTarget> : JsonConverter
    {
        protected Type conversionType;

        protected AbstractJsonConvertor()
        {
            conversionType = typeof(TTarget);
        }

        public override bool CanConvert(Type objectType)
        {
            bool isAssignableFrom = conversionType.IsAssignableFrom(objectType);
            return isAssignableFrom;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            const string messageFormat = "Convertion from json object to {0} is not supported !";
            throw new NotSupportedException(string.Format(messageFormat, conversionType.Name));
        }

        protected string Serialize(JsonSerializer serializer, object value)
        {
            StringWriter stringWriter = new StringWriter();
            serializer.Serialize(stringWriter, value);
            string serializedValue = stringWriter.ToString();
            return serializedValue;
        }
    }
}